package com.github.limit.advise;

import com.github.limit.context.LimitContext;
import com.github.limit.exception.AccessLimitException;
import com.github.limit.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author: wangdejun
 * @create: 2019-10-16 16:58
 **/
@Aspect
@Slf4j
@Order(-2)
public class LimitAdvise {

    @Autowired
    private LimitContext limitContext;

    private static ThreadLocal<JoinPoint> threadLocal = new ThreadLocal<>();

    public static final JoinPoint getJoinPoint() {
        return threadLocal.get();
    }


    @Pointcut(value = "this(com.github.limit.advise.LimitInterface)")
    public void pointCut() {

    }


    @Before(value = "pointCut()")
    public void beforeMethod(JoinPoint joinPoint) {
        proceed(joinPoint);
    }


    private void proceed(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        joinPoint.getArgs();
        boolean result = limitContext.start(method);
        if (!result) {
            throw new AccessLimitException("服务繁忙，请稍后重试");
        }
    }

    /**
     * 移除threadLocal变量，防止出现内存泄漏
     *
     * @param joinPoint
     */
    @After(value = "pointCut()")
    public void afterMethod(JoinPoint joinPoint) {
        threadLocal.remove();
    }


}
